const api = require('../../utils/api')
const { PaymentService } = require('../../utils/payment')
const app = getApp()
const request = require('../../utils/request')
const payment = require('../../utils/payment')
const cartSync = require('../../utils/cart-sync')

Page({
  data: {
    storeId: null,
    storeName: '',
    orderType: 'delivery',
    store: {},
    cartItems: [],
    
    // 配送信息
    selectedAddress: null,
    addressList: [],
    estimatedDeliveryTime: '',
    
    // 店内信息
    contactPhone: '',
    
    // 优惠券
    selectedCoupon: null,
    availableCoupons: [],
    
    // 备注
    remark: '',
    
    // 支付方式
    selectedPayment: 'wechat',
    paymentMethods: [
      {
        id: 'wechat',
        name: '微信支付',
        icon: '💳',
        selected: true
      },
      {
        id: 'alipay',
        name: '支付宝',
        icon: '💰',
        selected: false
      },
      {
        id: 'balance',
        name: '余额支付',
        icon: '💎',
        selected: false
      }
    ],
    
    // 费用计算
    productAmount: '0.00',
    deliveryFee: '0.00',
    discountAmount: '0.00',
    totalAmount: '0.00',
    
    // 弹窗状态
    showAddressModal: false,
    showCouponModal: false,
    
    // 提交状态
    submitting: false,
    canSubmit: false,
    
    // 配送时间
    deliveryTime: 'asap',
    scheduledTime: '',
    deliveryNote: '',
    
    // 餐具
    needTableware: true,
    tablewareCount: 1,
    
    // 发票
    needInvoice: false,
    invoiceTitle: '',
    invoiceTaxNumber: '',
    
    // 弹窗状态
    showPaymentModal: false,
    showTimeModal: false,
    showNoteModal: false,
    showInvoiceModal: false,
    
    // 计算属性
    selectedPaymentMethod: null,
    
    // 费用明细
    subtotal: '0.00',
    packagingFee: '2.00',
    discount: '0.00',
    
    // 订单信息
    orderInfo: null,
    // 商店信息
    storeInfo: null,
    // 送货地址
    address: null,
    // 可用支付方式
    paymentMethods: [
      { id: 'WECHAT_PAY', name: '微信支付', icon: '../../images/wechat_pay.png' },
      { id: 'ALIPAY', name: '支付宝', icon: '../../images/alipay.png' },
      { id: 'CASH', name: '货到付款', icon: '../../images/cash.png' }
    ],
    // 加载状态
    loading: false,
    // 支付金额
    payAmount: 0
  },

  onLoad(options) {
    console.log('订单页面接收到的参数:', options)
    const { storeId, storeName, orderType = 'delivery' } = options
    
    const parsedStoreId = parseInt(storeId)
    console.log('解析后的storeId:', parsedStoreId, '原始storeId:', storeId)
    
    this.setData({
      storeId: parsedStoreId,
      storeName: decodeURIComponent(storeName || ''),
      orderType,
      loading: true
    })
    
    this.initPage()
  },

  // 🎯 返回按钮处理
  goBack() {
    wx.vibrateShort();
    wx.navigateBack({
      fail: () => {
        // 如果无法返回，则跳转到首页
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    });
  },

  // 初始化页面
  async initPage() {
    await this.loadStoreInfo()
    this.loadCartItems()
    this.loadAddressList()
    this.loadCoupons()
    this.updateSelectedPaymentMethod()
    this.calculateAmount()
    this.checkCanSubmit()
    this.loadDefaultAddress()
    this.updatePayAmount()
    this.setData({ loading: false })
  },

  // 加载店铺信息
  async loadStoreInfo() {
    try {
      const res = await request.get('/stores/' + this.data.storeId, {}, {
        mock: {
          id: this.data.storeId,
          name: '美味餐厅',
          address: '广州市天河区天河路385号',
          phone: '020-12345678',
          businessHours: '10:00-22:00',
          deliveryFee: 5,
          minDeliveryAmount: 20,
          logo: 'https://img.yzcdn.cn/vant/cat.jpeg'
        }
      })
      
      if (res.code === 200 && res.data) {
        this.setData({
          storeInfo: res.data,
          deliveryFee: res.data.deliveryFee || 5
        })
        
        // 计算预计送达时间
        this.calculateDeliveryTime()
        
        // 重新计算支付金额
        this.updatePayAmount()
      }
    } catch (error) {
      console.error('加载店铺信息失败:', error)
    }
  },

  // 加载购物车商品
  loadCartItems() {
    const allCartItems = app.globalData.cart || []
    const targetStoreId = this.data.storeId
    
    console.log('=== 购物车数据加载调试 ===')
    console.log('全部购物车商品:', allCartItems)
    console.log('目标店铺ID:', targetStoreId, '类型:', typeof targetStoreId)
    
    // 调试每个购物车项目的storeId
    allCartItems.forEach((item, index) => {
      console.log(`商品 ${index}:`, {
        productId: item.productId,
        name: item.name,
        storeId: item.storeId,
        storeIdType: typeof item.storeId,
        matches: item.storeId === targetStoreId,
        matchesStrict: item.storeId == targetStoreId
      })
    })
    
    // 使用宽松比较来过滤商品（处理数据类型不匹配问题）
    const cartItems = allCartItems.filter(item => item.storeId == targetStoreId)
    
    console.log('过滤后的购物车数据:', cartItems)
    console.log('=== 调试结束 ===')
    
    if (cartItems.length === 0) {
      console.log('购物车为空，显示提示弹窗')
      wx.showModal({
        title: '提示',
        content: '购物车为空，是否返回选择商品？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
      return
    }
    
    // 为每个商品添加小计字段，统一字段名
    const processedCartItems = cartItems.map(item => ({
      ...item,
      imageUrl: item.image || item.imageUrl, // 统一图片字段名
      subtotal: (item.price * item.quantity).toFixed(2)
    }))
    
    console.log('处理后的购物车数据:', processedCartItems)
    this.setData({ cartItems: processedCartItems })
  },

  // 加载地址列表
  loadAddressList() {
    // 模拟地址数据
    const addressList = [
      {
        id: 1,
        receiverName: '张三',
        receiverPhone: '13800138001',
        address: '北京市朝阳区三里屯路19号院'
      },
      {
        id: 2,
        receiverName: '李四',
        receiverPhone: '13800138002',
        address: '北京市海淀区中关村大街1号'
      }
    ]
    
    this.setData({
      addressList,
      selectedAddress: addressList[0] // 默认选择第一个地址
    })
  },

  // 加载优惠券
  loadCoupons() {
    // 模拟优惠券数据
    const availableCoupons = [
      {
        id: 1,
        name: '满减优惠券',
        amount: 5,
        minAmount: 30
      },
      {
        id: 2,
        name: '新用户专享',
        amount: 10,
        minAmount: 50
      }
    ]
    
    this.setData({ availableCoupons })
  },

  // 计算配送时间
  calculateDeliveryTime() {
    const now = new Date()
    const deliveryTime = new Date(now.getTime() + 30 * 60000) // 30分钟后
    const timeStr = `${deliveryTime.getHours().toString().padStart(2, '0')}:${deliveryTime.getMinutes().toString().padStart(2, '0')}`
    this.setData({
      estimatedDeliveryTime: `今天 ${timeStr}`
    })
  },

  // 计算金额
  calculateAmount() {
    const productAmount = this.data.cartItems.reduce((total, item) => 
      total + (item.price * item.quantity), 0
    )
    
    const deliveryFee = this.data.orderType === 'delivery' ? parseFloat(this.data.deliveryFee) : 0
    const packagingFee = parseFloat(this.data.packagingFee) || 0
    const discountAmount = this.data.selectedCoupon ? this.data.selectedCoupon.amount : 0
    const totalAmount = productAmount + deliveryFee + packagingFee - discountAmount
    
    this.setData({
      productAmount: productAmount.toFixed(2),
      discountAmount: discountAmount.toFixed(2),
      totalAmount: Math.max(0, totalAmount).toFixed(2)
    })
    
    console.log('订单金额计算:', {
      productAmount: productAmount.toFixed(2),
      deliveryFee: deliveryFee.toFixed(2),
      packagingFee: packagingFee.toFixed(2),
      discountAmount: discountAmount.toFixed(2),
      totalAmount: Math.max(0, totalAmount).toFixed(2)
    })
  },

  // 检查是否可以提交
  checkCanSubmit() {
    let canSubmit = true
    let errorMessage = ''
    
    // 检查购物车是否为空
    if (!this.data.cartItems || this.data.cartItems.length === 0) {
      canSubmit = false
      errorMessage = '购物车为空'
    }
    
    // 外卖模式需要选择地址
    if (this.data.orderType === 'delivery' && !this.data.selectedAddress) {
      canSubmit = false
      errorMessage = '请选择收货地址'
    }
    
    // 店内模式需要填写手机号
    if (this.data.orderType === 'dine-in' && !this.data.contactPhone) {
      canSubmit = false
      errorMessage = '请填写联系电话'
    }
    
    // 检查支付方式
    if (!this.data.selectedPaymentMethod) {
      canSubmit = false
      errorMessage = '请选择支付方式'
    }
    
    // 检查总金额
    if (parseFloat(this.data.totalAmount) <= 0) {
      canSubmit = false
      errorMessage = '订单金额异常'
    }
    
    this.setData({ 
      canSubmit,
      submitErrorMessage: errorMessage
    })
  },

  // 选择地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/address/address?select=true'
    })
  },

  // 隐藏地址弹窗
  hideAddressModal() {
    this.setData({ showAddressModal: false })
  },

  // 选择地址项
  confirmAddress(e) {
    const addressId = e.currentTarget.dataset.id
    const address = this.data.addressList.find(item => item.id == addressId)
    this.setData({
      selectedAddress: address,
      showAddressModal: false
    })
    this.checkCanSubmit()
  },

  // 新增地址
  addAddress() {
    wx.navigateTo({
      url: '/pages/address/address'
    })
  },

  // 编辑地址
  editAddress(e) {
    e.stopPropagation()
    const addressId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/address-edit/address-edit?id=${addressId}`
    })
  },

  // 选择优惠券
  selectCoupon() {
    this.setData({ showCouponModal: true })
  },

  // 隐藏优惠券弹窗
  hideCouponModal() {
    this.setData({ showCouponModal: false })
  },

  // 选择优惠券项
  confirmCoupon(e) {
    const couponId = e.currentTarget.dataset.id
    const coupon = this.data.availableCoupons.find(item => item.id == couponId)
    this.setData({
      selectedCoupon: coupon,
      showCouponModal: false
    })
    this.calculateAmount()
  },

  // 不使用优惠券
  noCoupon() {
    this.setData({
      selectedCoupon: null,
      showCouponModal: false
    })
    this.calculateAmount()
  },

  // 更新选中的支付方式
  updateSelectedPaymentMethod() {
    const selectedMethod = this.data.paymentMethods.find(method => method.selected)
    this.setData({
      selectedPaymentMethod: selectedMethod || this.data.paymentMethods[0]
    })
  },

  // 选择支付方式
  selectPayment() {
    this.setData({ showPaymentModal: true })
  },

  // 确认支付方式
  confirmPayment(e) {
    const methodId = e.currentTarget.dataset.id
    const paymentMethods = this.data.paymentMethods.map(method => ({
      ...method,
      selected: method.id === methodId
    }))
    
    this.setData({
      paymentMethods,
      selectedPayment: methodId,
      showPaymentModal: false
    })
    
    this.updateSelectedPaymentMethod()
  },

  // 输入手机号
  onPhoneInput(e) {
    this.setData({ contactPhone: e.detail.value })
    this.checkCanSubmit()
  },

  // 输入备注
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 提交订单
  async submitOrder() {
    if (!this.data.canSubmit || this.data.submitting) return
    
    this.setData({ submitting: true })
    
    try {
      console.log('开始提交订单...')
      
      // 构建订单数据
      const orderData = {
        storeId: this.data.storeId,
        storeName: this.data.storeName,
        orderType: this.data.orderType,
        productAmount: parseFloat(this.data.productAmount),
        deliveryFee: parseFloat(this.data.deliveryFee),
        discountAmount: parseFloat(this.data.discountAmount),
        totalAmount: parseFloat(this.data.totalAmount),
        remark: this.data.remark,
        items: this.data.cartItems.map(item => ({
          productId: item.productId,
          productName: item.name,
          productImage: item.image,
          price: item.price,
          quantity: item.quantity,
          subtotal: item.price * item.quantity,
          specifications: item.specifications
        })),
        address: this.data.selectedAddress,
        paymentMethod: this.data.selectedPayment,
        coupon: this.data.selectedCoupon,
        deliveryTime: this.data.deliveryTime,
        scheduledTime: this.data.scheduledTime,
        deliveryNote: this.data.deliveryNote,
        needTableware: this.data.needTableware,
        tablewareCount: this.data.tablewareCount,
        needInvoice: this.data.needInvoice,
        invoiceTitle: this.data.invoiceTitle,
        invoiceTaxNumber: this.data.invoiceTaxNumber
      }
      
      // 外卖订单添加配送信息
      if (this.data.orderType === 'delivery' && this.data.selectedAddress) {
        orderData.deliveryAddress = JSON.stringify(this.data.selectedAddress)
        orderData.receiverName = this.data.selectedAddress.receiverName
        orderData.receiverPhone = this.data.selectedAddress.receiverPhone
      }
      
      // 店内订单添加联系电话
      if (this.data.orderType === 'dine-in') {
        orderData.receiverPhone = this.data.contactPhone
      }
      
      console.log('订单数据构建完成:', orderData)
      
      // 创建订单 - 添加API降级处理
      let orderResult
      try {
        orderResult = await api.createOrder(orderData)
        
        if (orderResult.code !== 200) {
          throw new Error(orderResult.message || '创建订单失败')
        }
      } catch (apiError) {
        console.log('API调用失败，使用模拟订单创建:', apiError.message)
        
        // API失败时创建模拟订单
        orderResult = {
          code: 200,
          message: '订单创建成功',
          data: {
            id: Date.now(), // 使用时间戳作为订单ID
            orderNo: 'ORD' + Date.now(),
            status: 'PENDING_PAYMENT',
            totalAmount: orderData.totalAmount,
            createdAt: new Date().toISOString(),
            ...orderData
          }
        }
        
        // 存储模拟订单到本地
        const mockOrders = wx.getStorageSync('mockOrders') || []
        mockOrders.push(orderResult.data)
        wx.setStorageSync('mockOrders', mockOrders)
      }
      
      const orderId = orderResult.data.id
      const totalAmount = this.data.totalAmount
      const paymentMethod = this.data.selectedPayment
      
      console.log('订单创建成功，开始支付:', { orderId, totalAmount, paymentMethod })
      
      // 执行支付
      try {
        const payment = new PaymentService()
        const paymentResult = await payment.pay(orderId, paymentMethod, totalAmount)
        
        console.log('支付成功:', paymentResult)
        
        // 清空当前店铺的购物车
        const allCart = app.globalData.cart
        const otherStoreItems = allCart.filter(item => item.storeId !== this.data.storeId)
        app.globalData.cart = otherStoreItems
        wx.setStorageSync('cart', otherStoreItems)
        
        // 显示支付成功
        wx.showModal({
          title: '支付成功',
          content: `订单已提交并支付成功\n订单号: ${orderResult.data.orderNo || orderId}`,
          showCancel: false,
          confirmText: '查看订单',
          success: () => {
            // 跳转到订单详情
            wx.navigateTo({
              url: `/pages/order-detail/order-detail?id=${orderId}`
            })
          }
        })
        
      } catch (paymentError) {
        console.error('支付失败:', paymentError)
        
        // 支付失败，但订单已创建，引导用户到订单列表重新支付
        if (paymentError.errorCode === 'USER_CANCEL') {
          wx.showModal({
            title: '支付已取消',
            content: '订单已创建，您可以稍后在订单列表中继续支付',
            confirmText: '去支付',
            cancelText: '稍后支付',
            success: (res) => {
              if (res.confirm) {
                wx.navigateTo({
                  url: `/pages/order-detail/order-detail?id=${orderId}&needPay=true`
                })
              } else {
                wx.switchTab({
                  url: '/pages/order-list/order-list'
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '支付失败',
            content: `${paymentError.message}\n订单已创建，请到订单列表重新支付`,
            confirmText: '重新支付',
            cancelText: '稍后支付',
            success: (res) => {
              if (res.confirm) {
                wx.navigateTo({
                  url: `/pages/order-detail/order-detail?id=${orderId}&needPay=true`
                })
              } else {
                wx.switchTab({
                  url: '/pages/order-list/order-list'
                })
              }
            }
          })
        }
      }
      
    } catch (error) {
      console.error('提交订单失败:', error)
      wx.showModal({
        title: '提交失败',
        content: error.message || '订单提交失败，请重试',
        showCancel: false,
        confirmText: '知道了'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 选择配送时间
  selectDeliveryTime() {
    this.setData({ showTimeModal: true })
  },

  // 确认配送时间
  confirmDeliveryTime(e) {
    const timeType = e.currentTarget.dataset.type
    
    if (timeType === 'asap') {
      this.setData({
        deliveryTime: 'asap',
        scheduledTime: '',
        showTimeModal: false
      })
    } else {
      // 预约配送时间选择
      wx.showModal({
        title: '选择配送时间',
        content: '请选择具体的配送时间',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              deliveryTime: 'scheduled',
              scheduledTime: '今天 18:00-19:00',
              showTimeModal: false
            })
          }
        }
      })
    }
  },

  // 添加备注
  addNote() {
    this.setData({ showNoteModal: true })
  },

  // 确认备注
  confirmNote(e) {
    const note = e.detail.value.trim()
    this.setData({
      deliveryNote: note,
      showNoteModal: false
    })
  },

  // 切换餐具
  toggleTableware() {
    this.setData({
      needTableware: !this.data.needTableware
    })
  },

  // 餐具数量变化
  onTablewareChange(e) {
    this.setData({
      tablewareCount: parseInt(e.detail.value)
    })
  },

  // 切换发票
  toggleInvoice() {
    if (!this.data.needInvoice) {
      this.setData({ showInvoiceModal: true })
    } else {
      this.setData({
        needInvoice: false,
        invoiceTitle: '',
        invoiceTaxNumber: ''
      })
    }
  },

  // 确认发票信息
  confirmInvoice(e) {
    const formData = e.detail.value
    this.setData({
      needInvoice: true,
      invoiceTitle: formData.title,
      invoiceTaxNumber: formData.taxNumber,
      showInvoiceModal: false
    })
  },

  // 关闭弹窗
  hideModal() {
    this.setData({
      showAddressModal: false,
      showPaymentModal: false,
      showCouponModal: false,
      showTimeModal: false,
      showNoteModal: false,
      showInvoiceModal: false
    })
  },

  // 获取默认地址
  async loadDefaultAddress() {
    const userId = app.getSafeUserId()
    
    const res = await request.get('/user/addresses/default', { userId }, {
      mock: {
        id: 1,
        name: '张三',
        phone: '13800138000',
        province: '广东省',
        city: '广州市',
        district: '天河区',
        detail: '天河路388号',
        isDefault: true
      }
    })
    
    if (res.code === 200 && res.data) {
      this.setData({ address: res.data })
    } else {
      // 没有默认地址时，提示用户添加
      wx.showToast({
        title: '请先添加收货地址',
        icon: 'none'
      })
    }
  },

  // 更新支付金额
  updatePayAmount() {
    const { totalAmount, deliveryFee, discountAmount } = this.data
    this.setData({
      payAmount: totalAmount + deliveryFee - discountAmount
    })
  }
}) 